package com.hc.controller;

import com.hc.base.ResultEnum;
import com.hc.base.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传
 */
@RestController
@Slf4j
@RequestMapping("file")
@Tag(name = "文件上传处理类")
public class FileController {

    //private static final String UPLOAD_FOLDER = System.getProperty("user.dir") + "upload/";
    private static final String UPLOAD_FOLDER ="home/data/upload/";

    private static  final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");



    /**
     * 文件上传服务
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @Operation(summary = "通用文件上传接口--单文件")
    public ResultVo upload(MultipartFile file) {
        log.info("文件名称为:" + file.getOriginalFilename() + "的文件大小为：" + file.getSize());
        String url="";
        try {
             url = saveFile(file);
        } catch (Exception e) {
            return ResultVo.error().message(ResultEnum.FILE_ERROR.getMessage());
        }
        return ResultVo.ok(url);
    }



    private String saveFile(MultipartFile f) throws IOException {

        String filePath = UPLOAD_FOLDER +f.getOriginalFilename();
       // String url = OssUtils.putObject(filePath, f.getInputStream());


        return "";
    }




    /**
     * 多文件上传
     */
    @PostMapping("multi/upload")
    @Operation(summary = "多文件上传")
    public  List<String> multiFilesUpload(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        if(null==multipartRequest){
            return null;
        }
        MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
        if(null==fileMap||fileMap.isEmpty()){
            return null;
        }

        List<String> urls = new ArrayList<>();

        for(Map.Entry<String, List<MultipartFile>> entry :fileMap.entrySet()){
            List<MultipartFile> files = entry.getValue();
            for(MultipartFile file:files){
                log.info("文件名称为:" + file.getOriginalFilename() + "的文件大小为：" + file.getSize());
                String url="";
                try {
                    url = this.saveFile(file);
                    urls.add(url);
                } catch (Exception e) {
                    log.info("多文件上传失败！");
                }
            }
        }
        return urls;
    }





    @RequestMapping(value ="ueditor/upload",method = {RequestMethod.POST,RequestMethod.GET})
    public Map upload(HttpServletRequest request, String action, HttpServletResponse response) {
        Map map = new HashMap();
        if(StringUtils.isNotBlank(action)){
            if(request instanceof MultipartHttpServletRequest){
                MultipartHttpServletRequest multipartHttpServletRequest =(MultipartHttpServletRequest)request;
                Iterator<MultipartFile> iterator = multipartHttpServletRequest.getFileMap().values().iterator();
                if(null != iterator){
                    if(iterator.hasNext()){
                        MultipartFile file = iterator.next();
                        String curfilekzmstr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
                        String fileToString = null;
                        try {
                            String s = this.saveFile(file);
//                            fileToString = MultipartFileUtil.encodeBase64MultipartFile(file);
//                            ResponseData responseData = ueditorUploadFileFeignClient.uploadFile(fileToString, "seller/", file.getOriginalFilename());
                            map.put("state","SUCCESS");
//                            Map sysAttachment = (Map)responseData.getData();
                            map.put("url",s);
                            map.put("original",file.getOriginalFilename());
                            map.put("type",curfilekzmstr);
                            map.put("size",file.getSize());
                            return map;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.setHeader("Access-Control-Allow-Headers", "Authorization");
        map.put("imageActionName","ueuploadimage");
        map.put("imageFieldName","upfile");
        map.put("imageMaxSize",51200000);
        map.put("imageAllowFiles",".png,.jpg,.jpeg,.gif,.bmp".split(","));
        map.put("imageCompressEnable",false);
        map.put("imageCompressBorder",1600);
        map.put("imageInsertAlign","none");
        map.put("imageUrlPrefix","");
        map.put("fileActionName","uploadfile");
        map.put("fileFieldName","upfile");
        map.put("fileUrlPrefix","");
        map.put("fileMaxSize",51200000);
        map.put("fileAllowFiles",".png,.jpg,.jpeg,.gif,.bmp,.flv,.swf,.mkv,.avi,.rm,.rmvb,.mpeg,.mpg,.ogg,.ogv,.mov,.wmv,.mp4,.webm,.mp3,.wav,.mid,.rar,.zip,.tar,.gz,.7z,.bz2,.cab,.iso,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.md,.xml".split(","));
        return map;
    }


}
